//
//  YKEspAPTwoViewController.m
//  DoorBell
//
//  Created by 王兴海 on 2021/7/14.
//  Copyright © 2021 王兴海. All rights reserved.
//

#import "YKEspAPTwoViewController.h"
#import "GCDAsyncSocket.h"
#import "BindSuccessViewController.h"
#import "VL4BLUViewController.h"
#import "FBWifiIModel.h"

#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>

#import "SimplePing.h"
#import "LDSRouterInfo.h"

@interface YKEspAPTwoViewController ()<UIScrollViewDelegate,GCDAsyncSocketDelegate,SimplePingDelegate,BindSuccessViewControllerDelegate>
@property(nonatomic,strong)UIScrollView *scrollview;
@property(nonatomic,strong)UIView *contrainView;
@property(nonatomic,strong)UILabel *oneLabel;
@property(nonatomic,strong)UILabel *wifiLabel;
@property(nonatomic,strong)UIImageView *iamgeView;
@property(nonatomic,strong)UILabel *twoLabel;
@property(nonatomic,strong)UILabel *tipsLabel;
@property(nonatomic,strong)UIButton *goButton;
@property(nonatomic,strong)GCDAsyncSocket *clientSocket;
@property(nonatomic,copy)NSString *devicesid;

//发送的数据
@property(nonatomic,strong)__block NSData *version_data;
@property(nonatomic,assign)__block NSUInteger post_count;
@property(nonatomic,assign)NSUInteger all_count;
@property(nonatomic,copy)NSString *dataPath;

@property (nonatomic,strong)dispatch_source_t e6_timer;

@property(nonatomic,strong)CLLocationManager *locationManager;

@property (nonatomic,strong)SimplePing *pinger;
@property (nonatomic,strong)dispatch_source_t pinger_timer;

@end


@implementation YKEspAPTwoViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
     self.scrollview.backgroundColor = [UIColor whiteColor];
     self.contrainView.backgroundColor = [UIColor whiteColor];
    
     NSRange range = [NSLocalizedString(@"1.请将手机WiFi连接到以CloudHome-Eques开头的WiFi;", nil) rangeOfString:@"CloudHome-Eques"];
     NSMutableAttributedString *newPrice = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"1.请将手机WiFi连接到以CloudHome-Eques开头的WiFi;", nil)];
     [newPrice addAttribute:NSForegroundColorAttributeName value:[HexChangeRGB colorWithHexString:@"#3B86DD"] range:range];
     self.oneLabel.attributedText = newPrice;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDevicesID:) name:@"addNewDevicesResponse" object:nil];
    
    NSRange range2 = [NSLocalizedString(@"WiFi密码：12345678", nil) rangeOfString:@"12345678"];
    NSMutableAttributedString *newPrice2 = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"WiFi密码：12345678", nil)];
    [newPrice2 addAttribute:NSForegroundColorAttributeName value:[HexChangeRGB colorWithHexString:@"#3B86DD"] range:range2];
    self.wifiLabel.attributedText = newPrice2;
    
    
    self.iamgeView.image = [UIImage imageNamed:@"ap_img_set_wifi"];
    
    self.twoLabel.text = NSLocalizedString(@"2.连接之后返回本应用，继续添加设备", nil);

    NSMutableAttributedString *fourLabelstring = [[NSMutableAttributedString alloc] initWithString:NSLocalizedString(@"", nil)];
    // 创建图片图片附件
    NSTextAttachment *fourattach = [[NSTextAttachment alloc] init];
    fourattach.image = [UIImage imageNamed:@"vl0_tips"];
    fourattach.bounds = CGRectMake(0, 3, 5, 5);
    NSAttributedString *fourattachString = [NSAttributedString attributedStringWithAttachment:fourattach];
    [fourLabelstring appendAttributedString:fourattachString];
    [fourLabelstring appendAttributedString:[[NSAttributedString alloc] initWithString:NSLocalizedString(@" 如果系统设置没有搜到该网络，请重新关闭、开启WiFi开关再搜索", nil)]];
     self.tipsLabel.attributedText = fourLabelstring;
    
    
    [self.goButton setTitle:NSLocalizedString(@"去设置WiFi", nil) forState:UIControlStateNormal];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ScanNavBarChange" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(APVIEW) name:@"ScanNavBarChange" object:nil];
    
    
    CGFloat phoneVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    // 如果是iOS13 未开启地理位置权限 需要提示一下
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined && phoneVersion >= 13) {
         self.locationManager = [[CLLocationManager alloc] init];
        [self.locationManager requestWhenInUseAuthorization];
    }
    
    if(@available(iOS 14.0,*)){
        //ios 14 检测本地网络是否开启
        [self start_local_net];
    }

  
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[self imageWithColor:WXHColor(255, 255, 255, 1.0)] forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
    
}

- (void)start_local_net
{
     NSDictionary *router = [LDSRouterInfo getRouterInfo];
    if ([router.allKeys containsObject:@"ip"]) {
        self.pinger = [[SimplePing alloc] initWithHostName:router[@"ip"]];
        self.pinger.delegate = self;
       [self.pinger start];
    }
}

- (void)simplePing:(SimplePing *)pinger didStartWithAddress:(NSData *)address {
    if (self.pinger_timer) {
        return;
    }
    self.pinger_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(self.pinger_timer, DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(self.pinger_timer, ^{
        [self.pinger sendPingWithData:nil];
    });
    dispatch_resume(self.pinger_timer);
}

- (void)simplePing:(SimplePing *)pinger didSendPacket:(NSData *)packet sequenceNumber:(uint16_t)sequenceNumber {
    NSLog(@"可以使用局域网");
      if(_pinger_timer){
         dispatch_source_cancel(_pinger_timer);
         _pinger_timer  = nil;
        [self.pinger stop];
         self.pinger = nil;
    }
}

- (void)simplePing:(SimplePing *)pinger didFailToSendPacket:(NSData *)packet sequenceNumber:(uint16_t)sequenceNumber error:(NSError *)error {
    if (error.code == 65) {//no route to host
        NSLog(@"不可以使用局域网");
        if(_pinger_timer){
            dispatch_source_cancel(_pinger_timer);
            _pinger_timer  = nil;
            [self.pinger stop];
             self.pinger = nil;
        }
        [self showAlertToOpenSettings];
    }
}


- (void)showAlertToOpenSettings {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Binding the device requires access to the local network permission of opening the app", nil)
                                                                             message:NSLocalizedString(@"Please go to Settings to enable local network access permissions", nil)
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *settingsAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Setting", nil)
                                                             style:UIAlertActionStyleDefault
                                                           handler:^(UIAlertAction * _Nonnull action) {
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:settingsURL]) {
            [[UIApplication sharedApplication] openURL:settingsURL options:@{} completionHandler:nil];
        }
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:settingsAction];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];

}


- (void)getDevicesID:(NSNotification*)notification
{
    NSDictionary *dict = [notification object];
    NSString *bid = [dict objectForKey:@"bid"];
    if (bid.length > 0) {
        self.devicesid = bid;
    }else{
        NSDictionary *new_dict = [dict objectForKey:@"added_bdy"];
        NSString *bid = [new_dict objectForKey:@"bid"];
        self.devicesid = bid;
    }
}

- (void)APVIEW
{
     
     //有时候热点不链接互联网 客户端获取不带ssid
    if ([[Tooles fetchSSIDInfo] containsString:@"CloudHome-Eques-16"] || ([Tooles fetchSSIDInfo] == nil && [[Tooles networkingStatesFromStatebar] isEqualToString:@"wifi"])) {
         [self.goButton setTitle:@"下一步" forState:UIControlStateNormal];
         [self readyBtnClick];
     }else{
         [self.goButton setTitle:@"去设置WiFi" forState:UIControlStateNormal];
     }
     
 }


- (UIScrollView*)scrollview
{
    if (!_scrollview) {
         _scrollview = [[UIScrollView alloc]init];
        if (@available(iOS 11.0, *)) {
            _scrollview.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
         _scrollview.showsVerticalScrollIndicator = NO;
         _scrollview.backgroundColor = WXHColor(242, 242, 242, 1.0);
        [self.view addSubview:_scrollview];
        [_scrollview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        
    }
    return _scrollview;
}


- (UIView*)contrainView
{
    if (!_contrainView) {
         _contrainView = [[UIView alloc]init];
        [self.scrollview addSubview:_contrainView];
        [_contrainView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.scrollview);
            make.width.equalTo(self.scrollview.mas_width);
        }];
    }
    return _contrainView;
}


- (void)setup
{
     self.title = NSLocalizedString(@"Connect to Hotspot", nil);
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,80,40);
     backbtn.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0f];
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setTitle:NSLocalizedString(@"back", nil) forState:UIControlStateNormal];
    [backbtn setTitleColor:[HexChangeRGB colorWithHexString:@"#4c4c4c"] forState:UIControlStateNormal];
    [backbtn setImage: [UIImage imageNamed:@"button_back_lightgray_arrow"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftAction) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];

}

- (void)selectLeftAction
{
    
    if (_clientSocket) {
        _clientSocket = nil;
    }
 
    [self.navigationController popViewControllerAnimated:YES];
    
}


-(UILabel*)oneLabel
{
    if (!_oneLabel) {
          _oneLabel = [[UILabel alloc]init];
          _oneLabel.numberOfLines = 0;
          _oneLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
          _oneLabel.textColor= [HexChangeRGB colorWithHexString:@"#333333"];
          _oneLabel.textAlignment = NSTextAlignmentLeft;
         [_oneLabel sizeToFit];
         [self.contrainView addSubview:_oneLabel];
         [_oneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contrainView.mas_left).offset(14);
            make.right.equalTo(self.contrainView.mas_right).offset(-4);
            make.top.equalTo(self.contrainView.mas_top).offset(20);
         }];
    }
    return _oneLabel;
}

-(UILabel*)wifiLabel
{
    if (!_wifiLabel) {
        _wifiLabel = [[UILabel alloc]init];
        _wifiLabel.numberOfLines = 0;
        _wifiLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
        _wifiLabel.textColor= [HexChangeRGB colorWithHexString:@"#333333"];
        _wifiLabel.textAlignment = NSTextAlignmentLeft;
         [_wifiLabel sizeToFit];
         [self.contrainView addSubview:_wifiLabel];
         [_wifiLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contrainView.mas_left).offset(14);
            make.right.equalTo(self.contrainView.mas_right).offset(-14);
            make.top.equalTo(self.oneLabel.mas_bottom);
         }];
    }
    return _wifiLabel;
}


-(UIImageView*)iamgeView
{
    if (!_iamgeView) {
         _iamgeView =[[UIImageView alloc]init];
        [self.contrainView addSubview:_iamgeView];
        [_iamgeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.contrainView.mas_centerX);
            make.height.mas_equalTo(200);
            make.width.mas_equalTo(320);
            make.top.equalTo(self.wifiLabel.mas_bottom).offset(20);
        }];
    }
    return _iamgeView;
}


-(UILabel*)twoLabel
{
    if (!_twoLabel) {
        _twoLabel = [[UILabel alloc]init];
        _twoLabel.numberOfLines = 0;
        _twoLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
         _twoLabel.textColor= [HexChangeRGB colorWithHexString:@"#333333"];
         _twoLabel.textAlignment = NSTextAlignmentLeft;
         [_twoLabel sizeToFit];
         [self.contrainView addSubview:_twoLabel];
         [_twoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contrainView.mas_left).offset(14);
            make.right.equalTo(self.contrainView.mas_right).offset(-14);
            make.top.equalTo(self.iamgeView.mas_bottom).offset(25);
         }];
    }
    return _twoLabel;
}


-(UILabel*)tipsLabel
{
    if (!_tipsLabel) {
          _tipsLabel = [[UILabel alloc]init];
          _tipsLabel.numberOfLines = 0;
          _tipsLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.0];
          _tipsLabel.textColor= [HexChangeRGB colorWithHexString:@"#666666"];
          _tipsLabel.textAlignment = NSTextAlignmentLeft;
         [_tipsLabel sizeToFit];
         [self.contrainView addSubview:_tipsLabel];
         [_tipsLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contrainView.mas_left).offset(14);
            make.right.equalTo(self.contrainView.mas_right).offset(-14);
            make.top.equalTo(self.twoLabel.mas_bottom).offset(10);
         }];
    }
    return _tipsLabel;
}





-(UIButton*)goButton
{
    if (!_goButton) {
         _goButton = [[UIButton alloc]init];
         _goButton.layer.cornerRadius = 8;
         _goButton.layer.masksToBounds = YES;
        _goButton.backgroundColor = [UIColor orangeColor];
        [_goButton addTarget:self action:@selector(readyBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.contrainView addSubview:_goButton];
        [_goButton mas_makeConstraints:^(MASConstraintMaker *make){
            make.width.mas_equalTo(260);
            make.height.mas_equalTo(44);
            make.top.equalTo(self.tipsLabel.mas_bottom).offset(75);
            make.centerX.equalTo(self.contrainView.mas_centerX);
            make.bottom.equalTo(self.contrainView.mas_bottom).offset(-60);
        }];
    }
    return _goButton;
}

- (void)readyBtnClick
{
    NSLog(@"[tooles networkingStatesFromStatebar]-->%@",[Tooles networkingStatesFromStatebar]);
    
    NSString *wifi_name = [Tooles fetchSSIDInfo];

    /*获取设备的Wi-Fi名称*/
    if ([wifi_name containsString:@"CloudHome-Eques-16"] || (wifi_name == nil && [[Tooles networkingStatesFromStatebar] isEqualToString:@"wifi"])) {

        
        VL4BLUViewController *vc = [[VL4BLUViewController alloc]init];
        vc.devicetype = self.devicetype;
        vc.bind_way = 0;
        vc.lock_id = nil;
        vc.is_support_screen = NO;
        vc.send_ip = self.send_ip;
       [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        
        NSString *str1_1 = @"A";
        NSString *str =  [str1_1 stringByAppendingFormat:@"p"];
        NSString *str0 = [str stringByAppendingFormat:@"p"];
        NSString *str2 = [str0 stringByAppendingFormat:@"-"];
        NSString *str3 = [str2 stringByAppendingFormat:@"P"];
        NSString *str4 = [str3 stringByAppendingFormat:@"r"];
        NSString *str5 = [str4 stringByAppendingFormat:@"e"];
        NSString *str6 = [str5 stringByAppendingFormat:@"fs"];
        NSString *str7 = [str6 stringByAppendingFormat:@":"];
        NSString *str8 = [str7 stringByAppendingFormat:@"r"];
        NSString *str9 = [str8 stringByAppendingFormat:@"o"];
        NSString *str10 = [str9 stringByAppendingFormat:@"o"];
        NSString *str11 = [str10 stringByAppendingFormat:@"t"];

         NSURL * settingURL = [NSURL URLWithString:str11];
        if ([[UIApplication sharedApplication] canOpenURL:settingURL]){

            [[UIApplication sharedApplication] openURL:settingURL options:@{} completionHandler:nil];

        }
    }
}


- (void)sendAP
{
    if (!self.clientSocket) {
         NSLog(@"start tcp service");
         self.clientSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
         NSError * error = nil;
        [self.clientSocket connectToHost:@"192.168.4.1" onPort:10001 error:&error];
        
    }
}


#pragma mark- GCDAsyncSocketDelegate
- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"tcp didConnect host -- >%@ port--->%d",host,port);
    self.clientSocket = sock;
    
    {
        NSString *main_ip,*sub_ip;
        YKIPinfo *appinfo = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
        if(appinfo.mainip){
            main_ip = appinfo.mainip;
            sub_ip = appinfo.subip;
        }
        NSLog(@"main_ip-->%@ sub_ip--%@",main_ip,sub_ip);
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        NSInteger timeOff = [zone secondsFromGMT];
        NSInteger timeMin = timeOff/60;//相差分钟数
        NSInteger zone2 = timeMin/60;//相差时区
        NSLog(@"timeOff == %ld timeMin == %ld zone2 == %ld\n",timeOff,timeMin,zone2);
        NSString *timezone;
        
        if(timeMin % 60 == 0){
            if(zone2 > 0){
                timezone = [NSString stringWithFormat:@"+%ld",(long)zone2];
            }else if(zone2 == 0){
                timezone = @"0";
            }else{
                timezone = [NSString stringWithFormat:@"%ld",(long)zone2];
            }
        }else{
            NSInteger zone3 = timeMin % 60;//相差分钟
            NSInteger zone2 = timeMin / 60;//相差小时
            if(zone2 > 0){
                timezone = [NSString stringWithFormat:@"+%ld:%ld",(long)zone2,zone3];
            }else if(zone2 == 0){
                timezone = [NSString stringWithFormat:@"0:%ld",(long)zone3];
            }else{
                timezone = [NSString stringWithFormat:@"%ld:%ld",(long)zone2,zone3];
            }
        }
        
        //连接成功 接收数据
        [sock readDataWithTimeout:-1 tag:0];
        
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setValue:self.wifi_name forKey:@"ssid"];
        [dict setValue:self.wifi_password forKey:@"pwd"];
        [dict setValue:[Tooles getuserToken] forKey:@"user_name"];
        [dict setValue:timezone forKey:@"time_zone"];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        int colony = [[userDefaults objectForKey:@"colony"] intValue];
        NSString *colony_addr = [userDefaults objectForKey:@"colony_addr"];
      
      if (colony_addr.length  > 0) {
          [dict setValue:@(colony) forKey:@"colony"];
          if (colony > 5) {
              [dict setValue:colony_addr forKey:@"colony_addr"];
          }
      }
        
        
        if (self.send_ip) {
            [dict setValue:main_ip forKey:@"main_ip"];
            [dict setValue:sub_ip forKey:@"sub_ip"];
        }
  
        [dict setValue:@(ThirdPartyDemoBrand) forKey:@"thirdPartyId"];
        
        
        NSError *error;
        // 将字典转换为 JSON 数据
        NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];

        
        [self.clientSocket writeData:data withTimeout:-1 tag:0];
        
    
    }
    
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
    NSLog(@"socketDidDisconnect withError-->%@",err);
    dispatch_async(dispatch_get_main_queue(), ^{
    
    });
}

- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    NSLog(@"发送数据回调--->%ld",tag);
}



- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    // 接收到回复数据处理
    NSString *receive = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"接收到数据---%@",receive);
   
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        // 登录上
        [self  login];
    });
}

-  (void)login
{
    if (![YKBusinessFramework equesIsLogin]) {
        
        YKIPinfo *info = [[YKIPinfo bg_find:@"YKIPinfo" where:nil] firstObject];
        if (info.auto_login) {
    
            [YKBusinessFramework loginWithUserName:info.user token:[Tooles getuserToken] appKey:ThirdPartyDemoAppKey server_adds:SERVER_ADDRS];
        }
    
    }
}




#pragma mark YKE1PROBindingAnimationDelegate
- (void)APOverTime
{
    if (_clientSocket) {
        _clientSocket = nil;
    }
    

    
}

- (void)BindSuccess
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
   
        NSArray *modelArray = [FBWifiIModel bg_find:@"FBWifiIModel" where:[NSString stringWithFormat:@"where %@=%@",bg_sqlKey(@"wifiName"),bg_sqlValue(self.wifi_name)]];
        
        if(modelArray.count > 0){
             FBWifiIModel *model = [modelArray firstObject];
             model.wifiPasswordName = self.wifi_password;
            [model bg_saveOrUpdate];
        }else{
             FBWifiIModel *model = [[FBWifiIModel alloc]init];
             model.wifiName = self.wifi_name;
             model.wifiPasswordName = self.wifi_password;
            [model bg_save];
        }
        
         BindSuccessViewController *vc = [[BindSuccessViewController alloc]init];
         vc.delegate = self;
         vc.modalPresentationStyle =  UIModalPresentationFullScreen;
        [self.view.window.rootViewController presentViewController:vc animated:YES completion:^{
    
        }];
    });
}


- (void)invalidatetime
{
    if (_clientSocket) {
        _clientSocket = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark BindSuccessViewControllerDelegate
- (void)didSeenewMydeviceBtnClick
{
    if (_clientSocket) {
        _clientSocket = nil;
    }
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeArea" object:nil];
    
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}



@end
